package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.apache.logging.log4j.util.Strings;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;

    /**
     * 对所有博客按照点赞数排序后分页返回数据
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            this.queryBlogUser(blog);
            this.isBlogLiked(blog);
                });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        //1.查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("数据不存在");
        }
        //2.查询blog有关的用户
        queryBlogUser(blog);
        //3.查询blog是否被点赞;
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        //1获取当前登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            //未登录
            return;
        }
        Long userId = user.getId();
        //2.判断当前登录用户是否已经点赞
        String key = "blog:liked:" + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //3.1 未点赞，设置未点赞
        //3.2 已点赞，设置已点赞
        blog.setIsLike(score != null);
//        // 如果 score 不为 null
//        if (score != null) {
//            blog.setIsLike(true);   // 标记为"已点赞"
//        } else {
//            blog.setIsLike(false);  // 标记为"未点赞"
//        }
//
//// 等价于上面的简化写法
//        blog.setIsLike(score != null);
//
   }
    /**
     * 博客点赞
     * @param id 博客id
     */
    @Override
    public Result likeBlog(Long id) {
        //1获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        //2.判断当前登录用户是否已经点赞
        String key = "blog:liked:" + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if(score == null){
            //3.如果未点赞，则点赞
            //3.1 数据库点赞数+1
            boolean isSuccess = update().setSql("liked = liked + 1")
                    .eq("id", id)
                    .update();
            if(isSuccess){
                //4.1 保存用户到RedisSet集合中
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        }
        //4.如果已点赞，则取消点赞
        //4.1 数据库点赞数-1
        else {
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            //4.2 删除用户从RedisSet集合中
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok( );
        }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
    /**
     * 返回当前博客已点赞的按时间先后的前五人
     *
     *
     */
    @Override
    public Result queryBlogLikes(Long id){
        //1、返回top5
        String key = "blog:liked:" + id;
        Set<String> Top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(Top5 == null || Top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //Long::valueOf等价于 Lambda 表达式：str -> Long.valueOf(str)
        // Redis返回的是字符串类型,但数据库查询需要Long类型
        List<Long> ids = Top5.stream().map(Long::valueOf).collect(Collectors.toList());//
        String idStr = Strings.join( ids, ',');
        //2、解析用户ID，查询用户信息
        List<UserDTO> userDTOList = userService.query()
                .in("id", ids)
                .last("ORDER BY FIELD(id," + idStr + ")")
                .list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        //3、封装用户信息并返回
        return Result.ok(userDTOList);
    }

    @Override
    public Result queryBlogByUserId(Integer current, Long id) {
        Page<Blog> page = query()
                .eq("user_id", id)
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
                List<Blog> records = page.getRecords();
                return Result.ok(records);
    }

    @Override
    public Result saveBlog(Blog blog) {
        //1.获取当前用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //2.保存探店笔记
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("新增笔记失败");
        }
        //3.查询笔记作者的粉丝
        List<Follow> followList = followService.query()
                .eq("follow_user_id", user.getId())
                .list();
        // 4.推送笔记
        for (Follow follow : followList) {
            // 5.1 获取粉丝id
            Long userId = follow.getUserId();
            String key = "feed:" + userId;
            // 5.2 推送笔记
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        //5.返回笔记id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.查询收件箱
        String key = "feed:" + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 3);
        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }
        //3.解析数据 (blogId, timestamp，offset)
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;//默认从1开始offset
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {//时间戳序列：1000, 1000, 1000, 999, 998，555，555
            // 3.1 获取blogId
            String blogId = tuple.getValue();
            ids.add(Long.valueOf(blogId));
            // 3.2 获取时间戳
            long time = tuple.getScore().longValue();
            if(time == minTime){
                os++;//score值与最小时间戳相同的元素个数，最后跳过这些重复元素
            } else {
                minTime = time;
                os = 1;
            }
        }
        //4.根据id查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Blog blog : blogs) {
            //5.查询blog的作者
            this.queryBlogUser(blog);
            //6.查询blog是否被点赞
            this.isBlogLiked(blog);
        }
        //5.封装数据并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }
}
